package com.example.springback.interceptor;

import com.example.springback.common.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头或者参数中拿 token
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getParameter("token");
        }
        // 校验 token
        if (token == null || !JWTUtil.verify(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            response.getWriter().write("无效的token，请重新登录！");
            return false;
        }
        // token 验证通过，继续执行
        return true;
    }
}
